<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人门户</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/users' }">研究机构</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="query">
            <template v-slot:append>
              <el-button @click="search" :icon="Search"></el-button>
              <!-- <el-icon class="el-icon--right"><Search /></el-icon> -->
            </template>
          </el-input>
        </el-col>
        <!-- 添加用户 -->
        <el-col :span="3">
          <el-button class="add-user" type="primary" @click="addUser"
            >新建研究机构</el-button
          >
        </el-col>
        <!-- 占空的 -->
        <el-col :span="15">
          <div></div>
        </el-col>
        <!-- 用户列表 -->
        <div class="table">
          <el-table
            :data="userlist"
            :default-sort="{ prop: 'id', order: 'ascending' }"
            stripe
            border
            class="userlist"
          >
            <el-table-column
              prop="user_id"
              label="序号"
              width="100%"
              sortable
            ></el-table-column>
            <el-table-column
              prop="name"
              label="姓名"
              width="100%"
              sortable
            >
            </el-table-column>
            <el-table-column prop="phone" label="电话" width="100%">
            </el-table-column>
            <el-table-column prop="company" label="科研机构" width="100%">
            </el-table-column>
            <el-table-column prop="department" label="专业领域" width="100%">
            </el-table-column>
            <el-table-column prop="influence" label="影响力" width="100%">
            </el-table-column>
            <!-- 操作 -->
            <el-table-column label="操作" width="100%">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="handleEdit(scope.row)"
                ></el-button>
                <el-button
                  type="info"
                  icon="el-icon-message"
                  circle
                ></el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="handleDelete(scope.row)"
                ></el-button>
                <!-- 身份切换开关 -->
                <el-switch
                  active-text="管理员"
                  inactive-text="用户"
                  v-model="scope.row.is_administrator"
                  @change="changeIdentity($event, scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            @current-change="getUserList"
            v-model:currentPage="queryInfo.pagenum"
            :page-size="10"
            layout="total, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-row>
    </el-card>

    <!-- 添加用户表格 -->
    <el-dialog title="新建用户" v-model="dialogVisible" width="40%">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
      </el-form>

      <div class="button-div">
        <el-form-item class="form-button">
          <el-button type="primary" @click="submitForm('ruleForm')"
            >创建</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </div>
    </el-dialog>

    <!-- 修改用户表格 -->
    <el-dialog title="修改用户信息" v-model="changedialogVisible" width="40%">
      <el-form
        :model="changeForm"
        :rules="rules"
        ref="changeForm"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <span>{{ changeForm.username }}</span>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="changeForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="changeForm.email"></el-input>
        </el-form-item>
      </el-form>

      <div class="button-div">
        <el-form-item class="form-button">
          <el-button type="primary" @click="submitChangeForm('changeForm')"
            >修改</el-button
          >
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
  import axios from "axios";
  import {Search} from '@element-plus/icons'
</script>
<script>
  export default {
    data() {
      return {
        query: "",
        queryInfo: {
          query: "",
          pagenum: 1,
        },
        userlist: [],
        total: 0,
        dialogVisible: false,
        ruleForm: {
          username: "",
          password: "",
          email: "",
        },
        rules: {
          username: [
            { required: true, message: "请输入用户名", trigger: "change" },
            {
              min: 1,
              max: 15,
              message: "长度在 1 到 15 个字符",
              trigger: "blur",
            },
          ],
          password: [
            { required: true, message: "请输入密码", trigger: "change" },
          ],
          email: [{ required: true, message: "请输入邮箱", trigger: "change" }],
        },
        changeForm: {
          username: "",
          password: "",
          email: "",
          is_administrator: null
        },
        changedialogVisible: false,
      };
    },
    created() {
      this.query = sessionStorage.getItem("query");
      this.getUserList();
    },
    methods: {
      getUserList() {
        axios.post("admin/users/", this.queryInfo).then((response) => {
          this.userlist = response.data.data;
          this.total = response.data.total;
        });
      },
      handleDelete(row) {
        this.$confirm("您是否确认删除该用户?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            axios
              .delete("/admin/users/" + row.username + "/")
              .then((response) => {
                console.log(response);
                this.getUserList();
              });
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      },
      handleEdit(row) {
        this.changedialogVisible = true;
        this.changeForm.username = row.username;
        this.changeForm.password = row.password;
        this.changeForm.email = row.email;
        this.changeForm.is_administrator = row.is_administrator
      },
      addUser() {
        this.dialogVisible = true;
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            axios.post("admin/users/add/", this.ruleForm).then((response) => {
              console.log(response.data);
              this.getUserList();
            });
            this.dialogVisible = false;
          } else {
            console.log("error submit!");
            return false;
          }
        });
      },
      resetForm() {
        this.changeForm.password = "";
        this.changeForm.email = "";

        this.ruleForm.username = "";
        this.ruleForm.password = "";
        this.ruleForm.email = "";
      },
      submitChangeForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            axios
              .put(
                "admin/users/" + this.changeForm.username + "/",
                this.changeForm
              )
              .then((response) => {
                console.log(response.data);
                this.getUserList();
              });
            this.changedialogVisible = false;
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      search() {
        this.queryInfo.query = this.query;
        this.getUserList();
        sessionStorage.setItem("query", this.query);
      },
      changeIdentity($event, row) {
        const formData = {
          username: row.username,
          password: row.password,
          email: row.email,
          is_administrator: row.is_administrator
        }
        axios
              .put(
                "admin/users/" + row.username + "/",
                formData
              )
              .then((response) => {
                console.log(response.data);
                this.getUserList();
              });
      },
    },
  };
</script>

<style scoped>
.box-card {
  margin-top: 20px;
}

.add-user {
  width: 100%;
  align-content: center;
  text-align: center;
}

.userlist {
  margin-top: 20px;
  margin-left: 10px;
  font-size: 13px;
  /* width: 98%; */
}

.el-table {
  width: fit-content;
}

.table {
  width: 100%;
}

.el-pagination {
  margin-left: 10px;
  margin-top: 10px;
}

.pagination {
  display: flex;
  justify-content: center;
  width: 100%;
  align-items: center;
}

.form-button {
  display: block;
  width: fit-content;
}

.button-div {
  display: flex;
  justify-content: center;
}

.el-switch {
  margin-left: 30px;
}
</style>
